from sqlalchemy.ext.asyncio import AsyncSession
from typing import List
from config.constant import CommonConstant
from exceptions.exception import ServiceException
from module_admin.entity.vo.common_vo import CrudResponseModel
from module_plant.dao.planter_dao import PlanterDao
from module_plant.entity.vo.planter_vo import DeletePlanterModel, PlanterModel, PlanterPageQueryModel
from utils.common_util import CamelCaseUtil
from utils.excel_util import ExcelUtil


class PlanterService:
    """
    种植主体信息模块服务层
    """

    @classmethod
    async def get_planter_list_services(
        cls, query_db: AsyncSession, query_object: PlanterPageQueryModel, is_page: bool = False
    ):
        """
        获取种植主体信息列表信息service

        :param query_db: orm对象
        :param query_object: 查询参数对象
        :param is_page: 是否开启分页
        :return: 种植主体信息列表信息对象
        """
        planter_list_result = await PlanterDao.get_planter_list(query_db, query_object, is_page)

        return planter_list_result


    @classmethod
    async def add_planter_services(cls, query_db: AsyncSession, page_object: PlanterModel):
        """
        新增种植主体信息信息service

        :param query_db: orm对象
        :param page_object: 新增种植主体信息对象
        :return: 新增种植主体信息校验结果
        """
        try:
            await PlanterDao.add_planter_dao(query_db, page_object)
            await query_db.commit()
            return CrudResponseModel(is_success=True, message='新增成功')
        except Exception as e:
            await query_db.rollback()
            raise e

    @classmethod
    async def edit_planter_services(cls, query_db: AsyncSession, page_object: PlanterModel):
        """
        编辑种植主体信息信息service

        :param query_db: orm对象
        :param page_object: 编辑种植主体信息对象
        :return: 编辑种植主体信息校验结果
        """
        edit_planter = page_object.model_dump(exclude_unset=True, exclude={})
        planter_info = await cls.planter_detail_services(query_db, page_object.planter_id)
        if planter_info.planter_id:
            try:
                await PlanterDao.edit_planter_dao(query_db, edit_planter)
                await query_db.commit()
                return CrudResponseModel(is_success=True, message='更新成功')
            except Exception as e:
                await query_db.rollback()
                raise e
        else:
            raise ServiceException(message='种植主体信息不存在')

    @classmethod
    async def delete_planter_services(cls, query_db: AsyncSession, page_object: DeletePlanterModel):
        """
        删除种植主体信息信息service

        :param query_db: orm对象
        :param page_object: 删除种植主体信息对象
        :return: 删除种植主体信息校验结果
        """
        if page_object.planter_ids:
            planter_id_list = page_object.planter_ids.split(',')
            try:
                for planter_id in planter_id_list:
                    await PlanterDao.delete_planter_dao(query_db, PlanterModel(planterId=planter_id))
                await query_db.commit()
                return CrudResponseModel(is_success=True, message='删除成功')
            except Exception as e:
                await query_db.rollback()
                raise e
        else:
            raise ServiceException(message='传入种植主体ID为空')

    @classmethod
    async def planter_detail_services(cls, query_db: AsyncSession, planter_id: int):
        """
        获取种植主体信息详细信息service

        :param query_db: orm对象
        :param planter_id: 种植主体ID
        :return: 种植主体ID对应的信息
        """
        planter = await PlanterDao.get_planter_detail_by_id(query_db, planter_id=planter_id)
        if planter:
            result = PlanterModel(**CamelCaseUtil.transform_result(planter))
        else:
            result = PlanterModel(**dict())

        return result

    @staticmethod
    async def export_planter_list_services(planter_list: List):
        """
        导出种植主体信息信息service

        :param planter_list: 种植主体信息信息列表
        :return: 种植主体信息信息对应excel的二进制数据
        """
        # 创建一个映射字典，将英文键映射到中文键
        mapping_dict = {
            'planterId': '种植主体ID',
            'year': '数据年份',
            'planterName': '主体名称',
            'planterType': '主体类型',
            'areaSizeMeasured': '实际量地面积',
            'county': '所在县',
            'village': '所在村',
            'areaSizeService': '托管服务面积',
            'measureState': '量地状态',
            'signState': '签约状态',
            'isRent': '是否需要支付地租',
            'pricipal': '种植主体负责人',
            'areaSizeFacility': '签约设施种植面积',
            'pricipalMobile': '负责人联系电话',
            'pricipalIdno': '负责人身份证号',
            'isSeed': '是否需要支付种苗款',
            'seedAmountEstimated': '种苗预估数量',
            'areaSizeOpenair': '露地签约面积',
            'seedAmount': '种苗数量',
            'taxerNo': '纳税人识别号',
            'bankAccountName': '银行开户名称',
            'memo': '备注',
            'areaSizePolicy': '村集体流转面积',
            'plantDensityOpenair': '露地种植密度',
            'plantDensityFacility': '设施种植密度',
            'bankAccount': '银行账号',
            'bankName': '开户银行',
        }
        binary_data = ExcelUtil.export_list2excel(planter_list, mapping_dict)

        return binary_data
